<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class CheckAdminLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        # 判断用户是否有登录，如果登录在这里面就会存储着用户的数据
        if(!auth()->check()){
            # 如果没有登录就跳转到登录页面去登录
            return redirect( route("admin.login"))->with("error","请先登录");
        }
        # 记录日志
//        Log::info("登录成功",auth()->user());
        # 如果有数据，那就向下执行代码
        # 得到访问当前页面路由别名
        $routeName = $request->route()->getName();
//        dump($routeName);
        # 得到用户模型
        $user_model = auth()->user();
//        dump($user_model);
        # 定义角色模型
        $role_model = $user_model->role;
        # 定义不能验证的权限
        $allWoLogin = [
            "admin.logout",
            "admin.index",
            "admin.welcome"
        ];
        # 得到当前的用户权限
        $nodeList = $role_model->nodes()->where("pid","<>",0)->pluck("route_name")->toArray();
        $nodeList = array_merge($nodeList,$allWoLogin);
//        dump($nodeList);
        $request->nodeList = $nodeList;
        $request->username = $user_model->username;
        # 判断如果是超级管理员就不用限制
        if($user_model->username != "admin" && !in_array($routeName,$nodeList)){
            die("没有权限");
        }
        return $next($request);
    }
}
